<template>
  <div
    v-if="!initializing"
    class="vc-component"
    :style="visual.parseStyle(currNode.currStyle)"
    @click="() => eventHandler.trigger('点击事件')"
  >
    <iframe
      :src="iframeUrl"
      :style="{
        width: width,
        height: height,
        border: 'none'
      }"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, inject, getCurrentInstance, onUnmounted } from 'vue'
import visual from "@/visual/js/visual";
import EventHandler from "@/visual/js/event";
import 'vue-cropper/dist/index.css';

const props = defineProps({
  node: Object,
  inputParam: Object
});
const initializing = ref(true);
const currNode = ref(props.node);
const eventHandler = new EventHandler(
  inject('eventHandler', Function, true),
  getCurrentInstance(),
  currNode.value
);

const loading = ref(true);
const iframeUrl = ref('');
const width = ref('');
const height = ref('');

const init = async(styleId) => {
  initializing.value = true;
  visual.initStyle(currNode.value, styleId);
  width.value = currNode.value.currCompStyle['width'] || '100%';
  height.value = currNode.value.currCompStyle['height'] || '100%';
  await refresh();
  await nextTick(() => initializing.value = false);
};

const loadValue = async() => {
  const dataList = (await visual.loadData(
    currNode.value.compData,
    eventHandler,
    getData(),
    currNode.value)).data || [];
  iframeUrl.value = dataList.length > 0 && dataList[0]['内容'] || '';
  loading.value = false;
};

const getData = () => {
  return {
    inputParam: Object.assign({}, currNode.value.inputParam, props.inputParam),
    value: iframeUrl.value
  };
};

const changeStyle = (styleId) => {
  init(styleId);
};

const refresh = async() => {
  initializing.value = true;
  await loadValue();
  await nextTick(() => initializing.value = false);
};

onMounted(async() => {
  await init();
  await loadValue();
  await eventHandler.trigger('初始化事件');
});

onUnmounted(() => {
  eventHandler.unregister();
});

defineExpose({ getData, changeStyle, refresh });
</script>

<style scoped>
</style>